﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Messaging;
using Sfd.Entities;
using SfdClient.Messaging;
using SfdClient.Resources;
using SfdClient.ViewModel;

namespace SfdClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private readonly DispatcherTimer _timer;
        private int _currentIcon;
        private readonly SynchronizationContext _syncContext;

        public MainWindow()
        {
            InitializeComponent();

            Trace.WriteLine(ResourceLocalizer.Current["MainWindow_Demarrage"], LogEntry.Verbose);

            _syncContext = SynchronizationContext.Current;
            // timer pour l'icône de notification
            _timer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 500) };
            _timer.Tick += TimerTick;

            // on reçoit un message comme quoi la propriété IsWorking du ViewModel a changée
            Messenger.Default.Register<PropertyChangedMessage<bool>>(this, message => IsWorkingPropertyChanged((PropertyChangedMessage<bool>) message));

            Messenger.Default.Register<NavigateToMessage>(this, message=>
                                                                    {
                                                                        if (ActiveControl != null)
                                                                            ActiveControl.Visibility = Visibility.Collapsed;

                                                                        switch (message.View)
                                                                        {
                                                                            case ApplicationView.AzureProjectsView:
                                                                                ActiveControl = azureProjectsView;
                                                                                break;
                                                                            case ApplicationView.AccountEditorView:
                                                                                ActiveControl = editorView;
                                                                                break;
                                                                            case ApplicationView.BrowserView:
                                                                                ActiveControl = browserView;
                                                                                break;
                                                                                case ApplicationView.SettingsView:
                                                                                ActiveControl = settingsView;
                                                                                break;
                                                                            default:
                                                                                throw new ArgumentException("message");
                                                                        }

                                                                        ActiveControl.Visibility = Visibility.Visible;
                                                                    });

            // on navigue vers le control par défaut
            Messenger.Default.Send(new NavigateToMessage(ApplicationView.AzureProjectsView));

            //Trace.WriteLine(string.Format("MAIN THREAD: {0}", System.Threading.Thread.CurrentThread.ManagedThreadId));
        }

        private UserControl ActiveControl { get; set; }

        private void IsWorkingPropertyChanged(PropertyChangedMessage<bool> message)
        {
            if (message == null || message.Sender == null)
                return;

            if (message.Sender.GetType() != typeof(AzureSyncProjectViewModel))
                return;

            if (message.PropertyName != WorkingViewModelBase.IsWorkingPropertyName)
                return;

            // l'action a effectuer
            // elle active le timer pour changer la forme de l'icône de notification
            Action<bool> action = (newValue) =>
            {
                if (newValue)
                {
                    if (!_timer.IsEnabled)
                    {
                        _timer.Start();
                    }
                }
                else
                {
                    _timer.Stop();
                    MyNotifyIcon.IconSource =
                        (BitmapImage)Application.Current.Resources["SfdStill"];
                }
            };

            if (Thread.CurrentThread.ManagedThreadId != Application.Current.Dispatcher.Thread.ManagedThreadId)
            {
                _syncContext.Send(d => action((bool)d), message.NewValue);
            }
            else
            {
                action(message.NewValue);
            }
        }

        /// <summary>
        /// Change l'aspect de l'icône de notification
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void TimerTick(object sender, EventArgs e)
        {
            _currentIcon++;
            if (_currentIcon == 3)
                _currentIcon = 1;

            MyNotifyIcon.IconSource = (BitmapImage) Application.Current.Resources[string.Format("SfdW{0}", _currentIcon)];
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (!this.IsVisible)
                this.Show();

            if (this.WindowState == WindowState.Minimized)
                this.WindowState = WindowState.Normal;

            this.Activate();
            this.Topmost = true;  
            this.Topmost = false;
            
            this.Focus();        

        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
                this.ShowInTaskbar = false;
            else
                this.ShowInTaskbar = true;
        }

    }
}
